package work.lrl.coupon_discard;

import cn.hutool.json.JSONObject;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import io.netty.channel.nio.NioEventLoopGroup;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import work.MemberUtil;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class Setup1 {
    public static void main(String[] args) {
        EasyExcel.read(Setting.setup1, ExcelObject.class, new Setup1Lis()).sheet().doRead();
    }

    public static class Setup1Lis implements ReadListener<ExcelObject> {
        List<ExcelObject> list = new CopyOnWriteArrayList<>();
        AtomicInteger count = new AtomicInteger();
        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(32);

        @Override
        public void invoke(ExcelObject excelObject, AnalysisContext analysisContext) {
            nioEventLoopGroup.execute(() -> {
                if (count.getAndIncrement() % 20 == 0) {
                    log.info("【卡券群发】发放 进度 ->{}", count.get());
                }
                list.add(excelObject);

                try {
                    discardCoupon(excelObject);
                } catch (Exception e) {
                    e.printStackTrace();
                    excelObject.setSuccess("否");
                }
            });
        }


        private void discardCoupon(ExcelObject excelObject) {
            JSONObject discardRes = MemberUtil.couponDiscard(excelObject.getCustomerId(), excelObject.get_id(), Setting.baseUrl, Setting.token);
            if (Objects.isNull(discardRes) || (!discardRes.containsKey("code")) || (!discardRes.getStr("code").equals("0"))) {
                log.error("【发放卡券】结果-》{}", discardRes);

                excelObject.setErrMsg(discardRes.toString());
                excelObject.setSuccess("否");

            } else {
                excelObject.setSuccess("是");
            }
        }

        @SneakyThrows
        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            nioEventLoopGroup.shutdownGracefully().sync();
            EasyExcel.write(Setting.resultFile, ExcelObject.class).sheet("sheet1").doWrite(list);

        }
    }
}
